import React from "react";
import ListSubheader from "@material-ui/core/ListSubheader";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import ListItemText from "@material-ui/core/ListItemText";
import IconButton from "@material-ui/core/IconButton";
import SendIcon from "@material-ui/icons/Send";
import MoreVertIcon from "@material-ui/icons/MoreVert";
import Fab from "@material-ui/core/Fab";
import AddIcon from "@material-ui/icons/Add";


// import SwipeableViews from "react-swipeable-views";
import { makeStyles, useTheme } from "@material-ui/core/styles";

import useService from "../../service/useService";
import service from "../../service";

// import GridForm from "../../components/GridForm";
import GridFormDialog from "../../components/GridFormDialog";

import Menu from "@material-ui/core/Menu";
import MenuItem from "@material-ui/core/MenuItem";

import { useAlertContext } from "../../contexts/AlertContext";
import {ProtoContext,ProtoProvider,useProtoContext} from "./context"


import _ from "lodash";



const useStyles = makeStyles((theme) => ({
	root: {
		width: "100%",
		// maxWidth: 360,
		backgroundColor: theme.palette.background.paper,
	},
	nested: {
		paddingLeft: theme.spacing(4),
	},
	displayFlex: {
		display: "flex",
	},
	displayFlexLeft: {
		display: "flex",
		justifyContent: "flex-start",
		alignItems: "center",
	},
	displayFlexRight: {
		display: "flex",
		justifyContent: "flex-end",
		flex: 1,
		alignItems: "center",
	},
	elementsRoot: {
		display: "flex",
		flexWrap: "wrap",
		// justifyContent: 'space-around',
		justifyContent: "flex-start",
		overflow: "hidden",
		backgroundColor: theme.palette.background.paper,
	},
	gridList: {
		width: 500,
		// minHeight: 300,
		alignContent: "flex-start",
	},
	listItemActive: {
		borderRadius: 3,
		boxShadow: "0px 3px 5px 2px rgba(255, 105, 135, .3)",
		// color: "red",
	},
	
}));


// modified proto class and then update it
async function refreshProtoClasses(setProtoClasses, setActiveClassId, setProtos, setActiveProtoId) {
	var { State, Data } = await service.graphElementProtoClasss.list();
	setProtoClasses(Data);
	if (Data && Data.length > 0) {
		if (setActiveClassId) {
			setActiveClassId(Data[0].Id);
		}
		if (setProtos) {
			let r = await service.graphElementProtos.list({ classId: Data[0].Id });
			setProtos(r.Data);
			if (setActiveProtoId && r.Data && r.Data.length > 0) {
				setActiveProtoId(r.Data[0].Id);
			}
		}
	}
}
// class edit menu
function ClassesMenu(props) {
	const { protoClasses, setProtoClasses, activeClassId, setActiveClassId, setProtos, setActiveProtoId } = React.useContext(ProtoContext);
	const [open, setOpen] = React.useState(false);

	const { anchorEl, setAnchorEl } = props;
	// var fields =[]
	if (activeClassId) {
		var activeClass = _.find(protoClasses, ["Id", activeClassId]);
		if (activeClass) {
			var fields = [
				{ name: "name", label: "Name", defaultValue: activeClass.Name },
				{ name: "no", label: "No", defaultValue: activeClass.No },
				{ name: "id", type: "hidden", defaultValue: activeClass.Id },
			];
		}
	}

	const { setError } = useAlertContext();

	const handleEdit = () => {
		setOpen(true);
		setAnchorEl(null);
	};
	const handleSubmit = async ($form) => {
		let r = await service.graphElementProtoClasss.update($form.serialize());
		if (r.State == 0) {
			let { Data } = await service.graphElementProtoClasss.list();
			setProtoClasses(Data);
			setOpen(false);
		} else {
			setError(r.Message);
		}
	};
	const handleDel = async () => {
		var r = await service.graphElementProtoClasss.delete(props.classId);
		if (r.State == 0) {
			await refreshProtoClasses(setProtoClasses, setActiveClassId, setProtos, setActiveProtoId);
		}else {
			setError("元素不为空，不能删除。")
		}
		setAnchorEl(null);
	};

	return (
		<>
			<GridFormDialog
				maxWidth="xs"
				open={open}
				setOpen={setOpen}
				handleClose={() => setOpen(false)}
				handleSubmit={handleSubmit}
				title="添加"
				fields={fields}
			></GridFormDialog>
			<Menu
				id="simple-menu"
				anchorEl={anchorEl}
				keepMounted
				open={Boolean(anchorEl)}
				onClose={() => {
					setAnchorEl(null);
				}}
			>
				<MenuItem onClick={handleEdit}>修改</MenuItem>
				<MenuItem onClick={handleDel}>删除</MenuItem>
			</Menu>
		</>
	);
}

// proto classes list
export default function ProtoClasses(props) {
	const classes = useStyles();
	const { setProto, setProtos, setProtoClasses, protoClasses, activeClassId, setActiveClassId } = React.useContext(ProtoContext);
	useService(async (service) => {
		var pcs = await service.graphElementProtoClasss.list();
		setProtoClasses(pcs.Data);
		if (pcs.Data && pcs.Data.length > 0) {
			handleClick(pcs.Data[0].Id);
		}
	}, []);
	// const [open, setOpen] = React.useState(true);
	// const [activeListItemId, setActiveListItemId] = React.useState(0);

	function handleClick(id) {
		setActiveClassId(id);
		props.onItemClick && props.onItemClick(id);
	}
	const [open, setOpen] = React.useState(false);
	// const [protoClasses, setProtoClasses] = React.useState([]);
	const handleAdd = (handleAdd) => {
		setOpen(true);
	};

	var fields = [{ name: "Name", label: "Name", xs: 12, autoFocus: true }];
	const handleSubmit = async ($form) => {
		var r = await service.graphElementProtoClasss.create($form.serialize());
		if (r.State == 0) {
			var pcs = await service.graphElementProtoClasss.list();
			setProtoClasses(pcs.Data);
		} else {
			console.log(r);
		}
		setOpen(false);
	};

	const [anchorEl, setAnchorEl] = React.useState(null);

	return (
		<>
			<ClassesMenu anchorEl={anchorEl} setAnchorEl={setAnchorEl} classId={activeClassId}></ClassesMenu>
			<GridFormDialog
				maxWidth="xs"
				open={open}
				setOpen={setOpen}
				handleClose={() => setOpen(false)}
				handleSubmit={handleSubmit}
				title="添加"
				fields={fields}
				form={{ method: "post" }}
			></GridFormDialog>
			<List
				component="nav"
				aria-labelledby="nested-list-subheader"
				subheader={
					<ListSubheader component="div" className={classes.displayFlex} id="nested-list-subheader">
						<div className={classes.displayFlexLeft}>图元分类</div>
						<div className={classes.displayFlexRight}>
							<IconButton onClick={handleAdd}>
								<AddIcon fontSize="inherit" />
							</IconButton>
						</div>
					</ListSubheader>
				}
				className={classes.root}
			>
				{protoClasses.map((v) => {
					return (
						<ListItem
							button
							onClick={handleClick.bind(this, v.Id)}
							key={v.Id}
							className={activeClassId == v.Id ? classes.listItemActive : ""}
						>
							<ListItemIcon>
								<SendIcon />
							</ListItemIcon>
							<ListItemText primary={v.Name} />
							<IconButton
								aria-label="more"
								size="small"
								onClick={(e) => {
									setAnchorEl(e.currentTarget);
								}}
							>
								<MoreVertIcon fontSize="inherit" />
							</IconButton>
						</ListItem>
					);
				})}
			</List>
		</>
	);
}


